import React, { useState } from 'react'
import { Send } from 'lucide-react'
import TopicSelector from '../kafka/TopicSelector'
import { ProducerMessage } from '../../pages/MessageProducer'

interface SingleMessageFormProps {
  topics: string[]
  selectedTopic: string
  partitions: number[]
  partitionsLoading: boolean
  onTopicChange: (topic: string | null) => void
  onProduceMessage: (message: ProducerMessage) => void
  isProducing: boolean
}

export function SingleMessageForm({
  topics,
  selectedTopic,
  partitions,
  partitionsLoading,
  onTopicChange,
  onProduceMessage,
  isProducing
}: SingleMessageFormProps) {
  const [message, setMessage] = useState<ProducerMessage>({
    key: '',
    value: '',
    headers: {},
    partition: undefined,
    format: 'text'
  })

  const [headersText, setHeadersText] = useState('')

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!selectedTopic || !message.value.trim()) {
      return
    }

    // 解析headers
    let headers: Record<string, string> = {}
    if (headersText.trim()) {
      try {
        headers = JSON.parse(headersText)
      } catch (error) {
        alert('Headers格式错误，请使用有效的JSON格式')
        return
      }
    }

    onProduceMessage({
      ...message,
      headers: Object.keys(headers).length > 0 ? headers : undefined
    })
  }

  const handleReset = () => {
    setMessage({
      key: '',
      value: '',
      headers: {},
      partition: undefined
    })
    setHeadersText('')
  }

  return (
    <div className="card hover-lift">
      <div className="card-header">
        <h2 className="card-title">发送单条消息</h2>
        <p className="card-description">配置消息内容和发送参数</p>
      </div>
      <div className="card-content">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Topic选择 */}
          <div className="relative">
            <TopicSelector
              topics={topics}
              selectedTopic={selectedTopic}
              onTopicChange={onTopicChange}
            />
          </div>

          {/* 消息Key */}
          <div className="bg-gray-50 p-4 rounded-lg border">
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              消息Key (可选)
            </label>
            <input
              type="text"
              value={message.key}
              onChange={(e) => setMessage(prev => ({ ...prev, key: e.target.value }))}
              placeholder="消息Key，用于分区路由"
              className="input w-full bg-white"
            />
            <p className="text-xs text-gray-500 mt-1">用于确定消息发送到哪个分区</p>
          </div>

          {/* 消息内容 */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="block text-sm font-semibold text-gray-700">
                消息内容 *
              </label>
              <select
                value={message.format}
                onChange={(e) => setMessage(prev => ({ ...prev, format: e.target.value as 'json' | 'text' | 'avro' }))}
                className="input w-24 text-xs bg-white border-gray-300 focus:border-gray-500"
              >
                <option value="text">文本</option>
                <option value="json">JSON</option>
                <option value="avro">Avro</option>
              </select>
            </div>
            <textarea
              value={message.value}
              onChange={(e) => setMessage(prev => ({ ...prev, value: e.target.value }))}
              placeholder={message.format === 'json' ? '{"key": "value"}' : '输入消息内容...'}
              rows={6}
              className="input w-full resize-none"
              required
            />
            <p className="text-xs text-gray-500 mt-1">
              {message.format === 'json' ? 'JSON格式的消息内容' :
               message.format === 'text' ? '普通文本消息内容' :
               'Avro格式的消息内容'}
            </p>
          </div>

          {/* Headers */}
          <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
            <label className="block text-sm font-semibold text-blue-700 mb-2">
              消息Headers (可选)
            </label>
            <textarea
              value={headersText}
              onChange={(e) => setHeadersText(e.target.value)}
              placeholder='{"header1": "value1", "header2": "value2"}'
              rows={3}
              className="input w-full bg-white border-blue-300 focus:border-blue-500"
            />
            <p className="text-xs text-blue-600 mt-1">JSON格式的消息头信息</p>
          </div>

          {/* 分区指定 */}
          <div className="bg-green-50 p-4 rounded-lg border border-green-200">
            <label className="block text-sm font-semibold text-green-700 mb-2">
              指定分区 (可选)
              {selectedTopic && (
                <span className="ml-2 text-xs font-normal">
                  {partitionsLoading ? (
                    <span className="text-blue-600">加载中...</span>
                  ) : partitions.length > 0 ? (
                    <span className="text-green-600">共 {partitions.length} 个分区 (0-{partitions.length - 1})</span>
                  ) : (
                    <span className="text-gray-500">无分区信息</span>
                  )}
                </span>
              )}
            </label>
            <div className="flex items-center space-x-3">
              <input
                type="number"
                value={message.partition ?? ''}
                onChange={(e) => setMessage(prev => ({
                  ...prev,
                  partition: e.target.value ? Number(e.target.value) : undefined
                }))}
                placeholder="分区号"
                min="0"
                max={partitions.length > 0 ? partitions.length - 1 : undefined}
                className="input w-32 bg-white border-green-300 focus:border-green-500"
              />
              {partitions.length > 0 && (
                <select
                  value={message.partition ?? ''}
                  onChange={(e) => setMessage(prev => ({
                    ...prev,
                    partition: e.target.value ? Number(e.target.value) : undefined
                  }))}
                  className="input w-40 bg-white border-green-300 focus:border-green-500"
                >
                  <option value="">自动选择</option>
                  {partitions.map(partition => (
                    <option key={partition} value={partition}>
                      分区 {partition}
                    </option>
                  ))}
                </select>
              )}
            </div>
            <p className="text-xs text-green-600 mt-1">留空则自动选择分区</p>
          </div>

          {/* 操作按钮 */}
          <div className="flex flex-col sm:flex-row gap-3 pt-4">
            <button
              type="submit"
              disabled={!selectedTopic || !message.value.trim() || isProducing}
              className="btn-primary hover-lift flex-1"
            >
              <Send className={`w-4 h-4 mr-2 ${isProducing ? 'animate-pulse' : ''}`} />
              {isProducing ? '发送中...' : '发送消息'}
            </button>
            <button
              type="button"
              onClick={handleReset}
              disabled={isProducing}
              className="btn-outline hover-lift"
            >
              重置表单
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
